<template>
<div class="keys-table">

    <el-alert
    title="提示消息"
    type="warning"
    center
    show-icon>
    <div style="margin-bottom:20px">1.下载授权文件或修改别名之前需要输入密码效验</div>
    <div style="margin-bottom:20px">2.第一次下载授权文件,需要给授权文件设置别名,别名类似于你的微信名,别名不能跟别人的别名重复,以后根据别名就能找到你的授权文件</div>
    <div>3.请不要使用别人已经设置好别名的授权文件,这样会导致驿站小秘无法正常使用!!!</div>
    </el-alert>
    <el-table
      size="small"
      height="300"
      border
      :data="displayKeysList"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="授权文件id"
        width="100">
      </el-table-column>
      <el-table-column
        prop="keys_name"
        label="授权文件名"
        width="380">
      </el-table-column>
      <el-table-column
        prop="alias"
        label="别名">
      </el-table-column>
      <el-table-column
        width='300px'
        label="操作">
         <template #default="{row}">
            <!-- 下载按钮 -->
            <el-button  type="primary" icon="el-icon-download" size="mini" @click="downloadKey(row)">下载授权文件</el-button>
            <el-button size="mini" icon="el-icon-edit" style="background-color:#ff6f98;color:#fff" @click="editAlias(row)">修改别名</el-button>
          </template>
      </el-table-column>
    </el-table>
    <el-pagination
      layout="prev, pager, next, total"
      :total="keysList.length"
      page-size=6
      @current-change="onHandleCurrentPageChange"
      >
    </el-pagination>
    <!-- 编辑对话框 -->
<el-dialog
  title="设置别名"
  :visible.sync="showSetAliasDialog"
  width="70%"
  >
     <el-form :model='aliasForm'  label-width='80px' ref='editForm' :rules="editrules">
    <el-form-item prop='alias' label='别名'>
         <el-input v-model="aliasForm.alias" placeholder="设置你的别名,别名类似你的微信名,以后可以根据别名找到你的授权文件"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="cancelEdit">取 消</el-button>
    <el-button type="primary" @click="submitEdit">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="输入密码"
  :visible.sync="showInputPassword"
  width="70%"
  >
     <el-form :model='inputPasswordForm'  label-width='80px' :rules="passwordRules">
    <el-form-item prop='password' label='密码'>
         <el-input v-model="aliasForm.alias" placeholder="请输入密码"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="cancelInput">取 消</el-button>
    <el-button type="primary" @click="submitPassword">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改别名"
  :visible.sync="showChangeAliasDialog"
  width="70%"
  >
     <el-form :model='changeAliasForm'  label-width='80px' ref='changeForm' :rules="changerules">
    <el-form-item prop='alias' label='别名'>
         <el-input v-model="changeAliasForm.alias" placeholder="修改你的别名"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="cancelEdit">取 消</el-button>
    <el-button type="primary" @click="submitChange">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>

<script>
import {getKeysList} from 'network/axios'
export default {
        name:'Etable',
        props:{
          isRefreshTable:{
            type:Boolean,
            default:false
          },
          search:{
            type:String,
            default:''
          },
          // 密码是否校验成功
          flag:{
            type:Number,
            required: true
          }
        },
        data(){
          return{
            // key列表
            keysList:[],
            // 要展示的key列表
            displayKeysList: [],
            inputPasswordForm:{
              password: ''
            },
            aliasForm:{
              alias:""
            },
            changeAliasForm:{
              alias: ''
            },
            // 密码输入对话框的显示与隐藏
            showInputPassword: false,
            //设置别名对话框的显示与隐藏
            showSetAliasDialog:false,
            // 修改别名对话框的显示与隐藏
            showChangeAliasDialog: false,
            //编辑时的验证规则
            editrules:{
              alias:[{
                required:"true",message:'别名不能为空',trigger:'blur'
              }]
            },
            changerules:{
              alias:[{
                required:"true",message:'别名不能为空',trigger:'blur'
              }]
            },
            keysInfo:{
              keys_name:'',
              id:0
            }
        }
        },
        created(){
          console.log(23)
          this.$bus.$on('search-key', element => {
            if (element === ''){
              this.displayKeysList = this.keysList.slice(0,6)
            }else{
              this.displayKeysList =  this.keysList.filter(val=>!element||(val.alias+'').includes(element))
            }
          })
           getKeysList().then(res=>{
             console.log(res);
             const arr1=res.data.filter(val=>{
               if(val.alias!=null&&val.alias!='')
               return true
             })
              console.log(arr1);
             const arr2=res.data.filter(val=>{
                if(val.alias===''||val.alias==null)
               return true
             })

             this.keysList=[...arr2,...arr1]
             this.displayKeysList = this.keysList.slice(0, 6)
           })
        
                      
        },
        methods:{
          async  downloadKey(row){
              if(this.flag){
                 this.keysInfo.keys_name=row.keys_name
              this.keysInfo.id=row.id
              if(row.alias){
                        this.$http({
               method:'get',
               url:`http://47.98.113.244:8889/api/private/v1/upload/keys/${row.keys_name}`,
               responseType: "arraybuffer"
           }).then(res=>{
              let blob = new Blob([res.data])
  // 生成a标签
  let downloadElement = document.createElement('a')
  // 创建下载的链接
  let href = window.URL.createObjectURL(blob)
  // a的下载链接
  downloadElement.href = href
  // 设置下载后文件名
  downloadElement.download = `${row.alias}授权文件.key`
  // 添加a标签
  document.body.appendChild(downloadElement)
  // 点击下载
  downloadElement.click()
  // 下载完成移除元素
  document.body.removeChild(downloadElement)
  // 释放掉blob对象
  window.URL.revokeObjectURL(href)
           }) 
              }
   else{
      this.showSetAliasDialog=true
   }
              }else{
                this.$message.error('请先进行密码校验')
              }
            },
            submitEdit(){
              this.$refs.editForm.validate(flag=>{
           
                if(flag)
                
                {
                        if(this.keysList.some(val=>val.alias===this.aliasForm.alias)){
              return this.$message.error('别名已经存在')
            }
                         this.$http({
                  method:'get',
                  url:`http://47.98.113.244:8889/api/private/v1/users/alias/${this.keysInfo.keys_name}/${this.aliasForm.alias}/${this.keysInfo.id}`
                }).then(res=>{
                  console.log(res);
                  if(res.data==='更新成功'){
                    this.showSetAliasDialog=false
                    this.$message.success('设置别名成功')
                    getKeysList().then(res=>{
             console.log(res);
             const arr1=res.data.filter(val=>{
               if(val.alias!=null&& val.alias!='')
               return true
             })
              console.log(arr1);
             const arr2=res.data.filter(val=>{
                if(val.alias==''||val.alias==null)
               return true
             })

             this.keysList=[...arr2,...arr1]

           })
                    this.$http({
                       method:'get',
               url:`http://47.98.113.244:8889/api/private/v1/upload/keys/${this.keysInfo.keys_name}`,
               responseType: "arraybuffer"
                    }).then(res=>{
                      const blob=new Blob([res.data])
                            let url=window.URL.createObjectURL(blob)
                            const a=document.createElement('a')
                            a.href=url
                            a.download=`${this.aliasForm.alias}授权文件.key`
                            document.body.appendChild(a)
                            a.click()
                            document.removeChild(a)
                            window.URL.revokeObjectURL(url)
    
                    })
                  }
                })
                }else{
                  this.$message.error('请根据提示输入有效的信息')
                }
               
              })
           
            },
            cancelEdit(){
              this.showChangeAliasDialog=false
              this.showSetAliasDialog=false
            },
            // 修改别名
            editAlias(row) {
              if(this.flag && row.alias!==''&&row.alias!==null){
                this.showChangeAliasDialog = true
                this.keysInfo.keys_name=row.keys_name
              this.keysInfo.id=row.id
                this.changeAliasForm.alias = row.alias
              }else{
                this.$message.error('您还没有进行密码校验或者该授权文件并没有设置过别名')
              }
            },
            submitChange(){
                  this.$refs.changeForm.validate(flag=> {
                  if(flag){
                    if(this.keysList.some(val=>val.alias===this.changeAliasForm.alias)){
                    return this.$message.error('别名已经存在')
                    }
                    this.$http({
                  method:'get',
                  url:`http://47.98.113.244:8889/api/private/v1/users/alias/${this.keysInfo.keys_name}/${this.changeAliasForm.alias}/${this.keysInfo.id}`
                }).then(res=>{
                  console.log(res);
                  if(res.data==='更新成功'){
                    this.showSetAliasDialog=false
                    this.$message.success('修改别名成功')
                    this.showChangeAliasDialog = false
                    getKeysList().then(res=>{
             console.log(res);
             const arr1=res.data.filter(val=>{
               if(val.alias!=null && val.alias!='')
               return true
             })
              console.log(arr1);
             const arr2=res.data.filter(val=>{
                if(val.alias==''||val.alias==null)
               return true
             })

             this.keysList=[...arr2,...arr1]

           })
              }
                  })
                  }else{
                    this.$message.error('请根据提示输入有效的信息')
                  }
                })
            },
            // 当前页码改变事件
            onHandleCurrentPageChange (currentPage) {
              this.displayKeysList = this.keysList.slice(currentPage*6-6,currentPage*6)
              console.log(this.displayKeysList)
              
            }
        }
          
}
</script>

<style scoped>
 .keys-table{
   padding-top: 20px;
   font-size: 20px;
 }
.el-table{
  margin-top:20px;
}
.alert{
  white-space: pre-wrap;
}
.el-pagination{
  text-align: center;
}
</style>